The localStorage
object allows you to save key-value pairs in a web browser with no expiration date.
This means the data stored persists even after the user closes the browser or restarts the computer.
localStorage
is a part of the Web Storage API that provides a way to store data in the browser.
Unlike cookies, the storage limit is much larger (around 5-10MB) and the data is not sent to the server with
every HTTP request.
To store data in localStorage
, use the setItem
method:
localStorage.setItem('key', 'value');
To retrieve data from localStorage
, use the getItem
method:
const value = localStorage.getItem('key');
To remove a specific item from localStorage
, use the removeItem
method:
localStorage.removeItem('key');
To clear all data from localStorage
, use the clear
method:
localStorage.clear();
localStorage
can only store strings. To store objects or arrays, you need to convert them to a
string using JSON.stringify
:
const user = { name: 'John', age: 30 };
localStorage.setItem('user', JSON.stringify(user));
To retrieve and parse the data back into an object:
const user = JSON.parse(localStorage.getItem('user'));
localStorage
, but always check
compatibility.localStorage
support before using it:if (typeof(Storage) !== 'undefined') {
// Code for localStorage
} else {
// No web storage support
}